package org.leno.houseHire.service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.leno.houseHire.action.LoginCondition;
import org.leno.houseHire.dao.ILoginDAO;
import org.leno.houseHire.dao.User;

public class LoginServiceImpl implements ILoginService {

	private ILoginDAO loginDAO;

	public void setLoginDAO(ILoginDAO loginDAO) {
		this.loginDAO = loginDAO;
	}

	public boolean valid(LoginDTO dto) {
		User pojo = new User();
		try {
			BeanUtils.copyProperties(pojo, dto);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		boolean flag = loginDAO.valid(pojo);
		if (flag) {
			dto.setUid(pojo.getUid());
		}
		return flag;
	}

	public void addLogin(LoginDTO dto) {

		User pojo = new User();
		try {
			BeanUtils.copyProperties(pojo, dto);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		loginDAO.addUser(pojo);

	}

	public int delLogin(List<String> ids) {
		return loginDAO.delUser(ids);
	}

	public void editLogin(LoginDTO dto) {

		User pojo = new User();
		try {
			BeanUtils.copyProperties(pojo, dto);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		loginDAO.editUser(pojo);

	}

	public List<LoginDTO> findAllLogin(LoginCondition cond, int start, int limit) {
		List<User> listPojo = loginDAO.findAllUser(cond, start, limit);
		List<LoginDTO> listDTO = new ArrayList<LoginDTO>();
		Iterator<User> it = listPojo.iterator();
		while (it.hasNext()) {
			User pojo = it.next();
			LoginDTO dto = new LoginDTO();
			try {
				BeanUtils.copyProperties(dto, pojo);
			} catch (IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			listDTO.add(dto);
		}
		return listDTO;
	}

	public LoginDTO findById(String id) {
		int intId = Integer.parseInt(id);
		User pojo = loginDAO.findById(intId);
		LoginDTO dto = new LoginDTO();
		try {
			BeanUtils.copyProperties(dto, pojo);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return dto;
	}

	public long getTotalNums(LoginCondition cond) {
		return loginDAO.getTotalNums(cond);
	}

}
